package com.stb.llh.controller;

import com.stb.llh.config.UserConfig;
import com.stb.llh.dao.UserDao;
import com.stb.llh.entity.User;
import com.stb.llh.service.UserService;
import com.stb.llh.util.ResJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Lee
 * @Date 2021/11/1
 * @Description
 */

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserDao userDao;


    @GetMapping("/login")
    public String login(){
            return "login/index";
    }

    @GetMapping("/outLogin")
    public String outLogin(HttpServletRequest req){

        if (req.getSession().getAttribute("user") != null) {
            req.getSession().invalidate();
            return "redirect:/login";
        }
        return "redirect:/login";
    }

    @PostMapping("/loginRes")
    @ResponseBody
    public String loginRes(HttpServletRequest req,HttpServletResponse res,String username,String pwd) {
        if ("post".equalsIgnoreCase(req.getMethod())) {
            System.out.println(username);
            System.out.println(pwd);

            User u = userService.checkUserandPwd(username, pwd);
            System.out.println(u);
//            User u = userDao.findById(1).get();

            if (u == null) {
                return ResJson.getError("登录失败");

            }
            req.getSession().setAttribute("user", u);

            System.out.println(ResJson.getSuccess("登录成功"));
            return ResJson.getSuccess("登录成功");
        }
        return ResJson.getError("登录失败");

    }

    @RequestMapping("/registry")
    public String registry(HttpServletRequest req){

            return "login/registry";
    }

    @PostMapping("/registryRes")
    @ResponseBody
    public String registyRes(HttpServletRequest req, String username, String pwd){

        System.out.println(username);
        System.out.println(pwd);

        User u = userService.checkUser(username);
        if(u != null){
            return ResJson.getError("用户已存在");
        }
        if (!userService.insertUser(username,pwd)) {
            return ResJson.getError("注册失败");
        }
        return ResJson.getSuccess("注册成功");
    }



//    针对管理员
        @GetMapping("/adminLogin")
        public String adminLogin(){
            return "login/adminLogin";
        }



}
